<?php

namespace mbilling\BillingBundle\Services;

class JabberWebbridge implements JabberInterface
{
    protected $mysql_user;
    protected $mysql_password;
    protected $mysql_server;
    protected $mysql_port;
    protected $waiting_time;
    protected $securityContext;
    protected $session;
    
    public function __construct($securityContext, $session, $service_container)
    {
        $parameters = $service_container->getParameter('webbridge');
        $this->mysql_user = $parameters['mysql_user'];
        $this->mysql_password = $parameters['mysql_password'];
        $this->mysql_server = $parameters['mysql_server'];
        $this->mysql_dbname = $parameters['mysql_dbname'];
        $this->mysql_port = $parameters['mysql_port'];
        $this->waiting_time = $parameters['waiting_time'];
        $this->securityContext = $securityContext;
        $this->session = $session;
    }

    public function waitMessage($message_id)
    {
        $session = md5('session'.getenv('HTTP_USER_AGENT').getenv("REMOTE_ADDR"));
    
        $time = time();
        $end = $time + $this->waiting_time;
        $output = array();
        while($time < $end)
        {
            $time = time();
            sleep(1);
            $mysql = mysql_connect($this->mysql_server.':'.$this->mysql_port, $this->mysql_user, $this->mysql_password)
            or die("Could not connect: " . mysql_error());
            mysql_select_db($this->mysql_dbname) or die("Could not select database");
            $query = "SELECT * FROM request_answer where id='".$message_id."' and session='".$session."'";
            $result = mysql_query($query) or die("Query failed : " . mysql_error());
            $output = mysql_fetch_array($result, MYSQL_ASSOC);

            mysql_free_result($result);
            mysql_close($mysql);
            
            if ($output['is_finished'])
            {
                $output['reply'] = preg_replace("/<fipa(.)*<content>/", '', $output['reply']);
                $output['reply'] = preg_replace("/\(=(.)*\) \((\")?/", '', $output['reply']);
                $output['reply'] = preg_replace("/(\")?(\))*/", '', $output['reply']);
                $output['reply'] = preg_replace("/<\/content>(.)*-message>/", '', $output['reply']);
                if ( (($output['reply_action']) == "refuse") || (($output['reply_action']) == "failure") )
                {
                    $res = array();
                    $res['error'] = $output['reply'];
                    return $res;
                }
                //print_r($output);
                $res = explode("\n", $output['reply']);
                if (count($res) > 1)
                    array_pop($res);
                if ($res['0'] == '')
                    return array();
                return $res;
            }
        }
        return array('error' => 'No responding from server');
    }

    public function sendMessage($action, $params = array())
    {
        //1 - создание нового виртуального диска
        //2 - активация виртуального диска
        //3 - деактивация виртуального диска
        //4 - получение видимых AoE exports для виртуального диска
        //5 - информация о доступном месте на hdd
        //6 - информация о доступном памяти
        //7 - проверка состояния виртуального диска
        //8 - проверка состояния виртуального сервера
        //9 - получение списка mysql пользователей
        //10- создание нового mysql пользователя
        //11- получение списка баз данных
        //12- создание новой базы данных
        //13- получение списка пользователей имеющих права на базу
        //14- получение списка прав пользователей на базу
        //15- удаление mysql пользователя
        //16- создание unix пользователя и его домашней директории
        //17- удаление unix пользователя
        //18- удаление базы данных
        //19- получение списка ящиков почты
        //20- создание нового ящика почты
        //21- удаление ящика почты
        //22- изменение пароля ящика почты
        //23- изменение пароля mysql пользователя
        //24- изменение прав mysql пользователя
        //25- создание FTP пользователя
        //26- удаление FTP пользователя
        //27- изменение FTP пользователя
        //28- список FTP пользователей с их папками
        //29- создание dns записи
        //30- удаление dns записи
        //31- изменение dns записи
        //32- синхронизация dns записей домена
        //33- создание домена
        //34- удаление домена
        //35- синхронизация доменов
        //36- синхронизация подсетей
        //37- синхронизация ip-адресов
        //38- создание ip-адреса
        //39- удаление ip-адреса
        //40- изменение ip-адреса
        //41- создание подсети
        //42- удаление подсети
        //43- изменение подсети
        
        switch ($action)
        {
            case 1:
                $ontology = "cirrocumulus-xen";
                $action = "request";
                $content = '(create (raid (disk_number '.$disk_number.') (size '.$size.')))';
            break;
            case 2:
                $ontology = "cirrocumulus-xen";
                $action = "request";
                $content = '(start (raid '.$disk_number.'))';
            break;
            case 3:
                $ontology = "cirrocumulus-xen";
                $action = "request";
                $content = '(stop (raid '.$disk_number.'))';
            break;
            case 4:
                $ontology = "cirrocumulus-xen";
                $action = "query-ref";
                $content = '(state (aoe '.$disk_number.'))';
            break;
            case 5:
                $ontology = "cirrocumulus-storage";
                $action = "query-ref";
                $content = '(free_space)';
            break;
            case 6:
                $ontology = "cirrocumulus-xen";
                $action = "query-ref";
                $content = '(free_memory)';
            break;
            case 7:
                $ontology = "cirrocumulus-xen";
                $action = "query-ref";
                $content = '(state (raid '.$disk_number.'))';
            break;
            case 8:
                $ontology = "cirrocumulus-xen";
                $action = "query-if";
                $content = '(running (domu "DOMU_NAME"))';
            break;
            case 9:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (mysql_user '.$params['prefix'].'))';
            break;
            case 10:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (mysql_user '.$params['login'].' '.$params['name'].' '.$params['password'].' '.$params['rights'].'))';
            break;
            case 11:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (database '.$params['prefix'].'))';
            break;
            case 12:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (database '.$params['name'].'))';
            break;
            case 13:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (database_user '.$params['prefix'].'))';
            break;
            case 14:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (database_privelege '.$params['prefix'].'))';
            break;
            case 15:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (mysql_user '.$params['login'].' '.$params['name'].'))';
            break;
            case 16:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (unix_user '.$params['password'].'))';
            break;
            case 17:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (unix_user '.$params['login'].'))';
            break;
            case 18:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (database '.$params['name'].'))';
            break;
            case 19:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (mail '.$params['user'].'))';
            break;
            case 20:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (mail '.$params['user'].' '.$params['email'].' '.$params['password'].'))';
            break;
            case 21:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (mail '.$params['user'].' '.$params['email'].'))';
            break;
            case 22:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (mail '.$params['user'].' '.$params['email'].' '.$params['password'].'))';
            break;
            case 23:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (mysql_user_password '.$params['name'].' '.$params['login'].' '.$params['password'].'))';
            break;
            case 24:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (mysql_user_rights '.$params['name'].' '.$params['login'].' '.$params['rights'].'))';
            break;
            case 25:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (ftp_user '.$params['full_login'].' '.$params['password'].' '.$params['dir'].'))';
            break;
            case 26:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (ftp_user '.$params['full_login'].'))';
            break;
            case 27:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (ftp_user '.$params['full_login'].' '.$params['password'].'))';
            break;
            case 28:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (ftp_user '.$params['user'].'))';
            break;
            case 29:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (dns '.$params['domain'].' '.$params['name'].' '.$params['type'].' '.$params['value'].'))';
            break;
            case 30:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (dns '.$params['domain'].' '.$params['name'].' '.$params['type'].' '.$params['value'].'))';
            break;
            case 31:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (dns '.$params['domain'].' '.$params['source'].' '.$params['dest'].'))';
            break;
            case 32:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (dns '.$params['domain'].'))';
            break;
            case 33:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (domain '.$params['domain'].' '.$params['dns_string'].'))';
            break;
            case 34:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (domain '.$params['domain'].'))';
            break;
            case 35:
                $ontology = "vh-master";
                $action = "request";
                $content = '(synch (domain))';
            break;
            case 36:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (dhcp_net))';
            break;
            case 37:
                $ontology = "vh-master";
                $action = "query-ref";
                $content = '(show (dhcp_ip))';
            break;
            case 38:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (dhcp_ip '.$params['ip'].' '.$params['name'].' '.$params['mac'].' '.$params['type'].' '.$params['owner'].'))';
            break;
            case 39:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (dhcp_ip '.$params['ip'].' '.$params['mac'].'))';
            break;
            case 40:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (dhcp_ip '.$params['source'].' '.$params['dest'].'))';
            break;
            case 41:
                $ontology = "vh-master";
                $action = "request";
                $content = '(create (dhcp_net '.$params['ip'].'))';
            break;
            case 42:
                $ontology = "vh-master";
                $action = "request";
                $content = '(drop (dhcp_net '.$params['ip'].'))';
            break;
            case 43:
                $ontology = "vh-master";
                $action = "request";
                $content = '(change (dhcp_net '.$params['source_ip'].' '.$params['dest_ip'].'))';
            break;
            default:
                $ontology = '';
                $action = '';
                $content = '';
            break;
        }
        //$message = htmlentities($message, ENT_QUOTES, 'utf-8');

        $userCurrent = $this->securityContext->getToken()->getUser();
        $session = md5('session'.getenv('HTTP_USER_AGENT').getenv("REMOTE_ADDR"));
        $mysql = mysql_connect($this->mysql_server.':'.$this->mysql_port, $this->mysql_user, $this->mysql_password)
        or die("Could not connect: " . mysql_error());
        mysql_select_db($this->mysql_dbname) or die("Could not select database");
        $query = "INSERT INTO request_answer(user_id, session, ontology, action, content) VALUES ('".$userCurrent->getId()."', '$session', '$ontology', '$action', '$content')";
        $result = mysql_query($query) or die("Query failed : " . mysql_error());
        //mysql_free_result($result);

        if ($userCurrent->isAdmin() && $this->session->get('user'))
            $query = "SELECT max(id) FROM request_answer WHERE user_id='".$this->session->get('user')->getId()."' GROUP BY user_id";
        else
            $query = "SELECT max(id) FROM request_answer WHERE user_id='".$userCurrent->getId()."' GROUP BY user_id";
        $result = mysql_query($query) or die("Query failed : " . mysql_error());
        $array = mysql_fetch_array($result);
        $id = $array['max(id)'];
        //mysql_free_result($result);
        mysql_close($mysql);
        return $id;
    }
    
    public function checkMessage($message_id)
    {
        $session = md5('session'.getenv('HTTP_USER_AGENT').getenv("REMOTE_ADDR"));
        
        $mysql = mysql_connect($this->mysql_server.':'.$this->mysql_port, $this->mysql_user, $this->mysql_password)
        or die("Could not connect: " . mysql_error());
        mysql_select_db($this->mysql_dbname) or die("Could not select database");
        $query = "SELECT * FROM request_answer where id='".$message_id."' and session='".$session."'";
        $result = mysql_query($query) or die("Query failed : " . mysql_error());
        $output = mysql_fetch_array($result, MYSQL_ASSOC);
        mysql_free_result($result);
        mysql_close($mysql);
        if ($output['is_finished'])
        {
            $output['content'] = str_replace("(", "", $output['content']);
            $output['content'] = str_replace(")", "", $output['content']);
            if ( (($output['reply_action']) == "refuse") || (($output['reply_action']) == "failure") )
            {
                $output['reply'] = preg_replace("/<fipa(.)*<content>/", '', $output['reply']);
                $output['reply'] = preg_replace("/\(=(.)*\) \((\")?/", '', $output['reply']);
                $output['reply'] = preg_replace("/(\")?(\))*/", '', $output['reply']);
                $output['reply'] = preg_replace("/<\/content>(.)*-message>/", '', $output['reply']);
                return $output['reply']."::".$output['content'];
            }
            else
                return "ok"."::".$output['content'];
        }
        else
            return "no"."::".$output['content'];
    }
}
/*Select
Insert 
Update
Delete 
Create
Drop 
Alter
Index 
Grant
Reference 
Create tmp tables
Lock Tables*/